package com.glxy.wxtakeaway.controller;

import com.glxy.wxtakeaway.entity.CabinetInfo;
import com.glxy.wxtakeaway.mapper.CabinetMapper;
import com.glxy.wxtakeaway.vo.Result;
import com.glxy.wxtakeaway.utils.CabinetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/cabinets")
public class CabinetController {

    private static final Logger logger = LoggerFactory.getLogger(CabinetController.class);

    @Resource
    private CabinetMapper cabinetMapper;

    // 取餐员查询有多少商品
    @PostMapping("/check")
    public Result<Object> checkCabinet(@RequestBody CabinetInfo cabinetInfo) {
        Result<Object> result = new Result<>();

        String cabinetName = CabinetUtils.buildCabinetName(cabinetInfo.getCabinetName());
        String phoneNumber = cabinetInfo.getPhoneNumber();

        // 校验手机尾号（4位）
        if (!CabinetUtils.isValidPhoneTail(phoneNumber)) {
            result.setCode(400);
            result.setMessage("手机尾号格式不正确，请输入4位手机尾号");
            return result;
        }

        try {
            List<Result> cabinetNumbers = cabinetMapper.selectByPhoneNumber(cabinetName, phoneNumber);
            if (!cabinetNumbers.isEmpty()) {
                result.setCode(200);
                result.setMessage("查询成功");
                result.setData(cabinetNumbers);
                logger.info("查询成功：cabinetName={}, phoneNumber={}", cabinetName, phoneNumber);
            } else {
                result.setCode(404);
                result.setMessage("未有该号码！");
                logger.warn("未找到对应柜子：cabinetName={}, phoneNumber={}", cabinetName, phoneNumber);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("系统错误，请稍后重试");
            logger.error("查询柜子失败：", e);
        }

        return result;
    }

    // 打开柜子（送餐员：11位；取餐员：4位）
    @PostMapping("/open")
    public Result<Object> openCabinet(@RequestBody CabinetInfo cabinetInfo) {
        Result<Object> result = new Result<>();

        String cabinetName = CabinetUtils.buildCabinetName(cabinetInfo.getCabinetName());
        String phoneNumber = cabinetInfo.getPhoneNumber();
        Integer cabinetId = cabinetInfo.getId();

        // 校验手机号格式
        if (phoneNumber.length() == 4 && !CabinetUtils.isValidPhoneTail(phoneNumber)) {
            result.setCode(400);
            result.setMessage("手机尾号格式不正确，请输入4位手机尾号");
            return result;
        } else if (phoneNumber.length() == 11 && !CabinetUtils.isValidPhoneNumber(phoneNumber)) {
            result.setCode(400);
            result.setMessage("手机号格式不正确，请输入11位有效手机号");
            return result;
        } else if (phoneNumber.length() != 4 && phoneNumber.length() != 11) {
            result.setCode(400);
            result.setMessage("手机号码格式不正确，请输入4位手机尾号或11位手机号码");
            return result;
        }

        if (cabinetId == null) {
            result.setCode(400);
            result.setMessage("cabinetId 不能为空");
            return result;
        }

        try {
            boolean isSuccess;
            String role;

            if (phoneNumber.length() == 4) {
                // 取餐员打开柜子
                isSuccess = cabinetMapper.openCabinetForPickup(cabinetName, cabinetId);
                role = "取餐员";
            } else {
                // 送餐员打开柜子
                isSuccess = cabinetMapper.openCabinetForDeliveryman(cabinetName, phoneNumber);
                role = "送餐员";
            }

            if (isSuccess) {
                result.setCode(200);
                result.setMessage(role + "打开柜子成功");
                logger.info("{} 打开柜子成功：cabinetName={}, phoneNumber={}", role, cabinetName, phoneNumber);
            } else {
                result.setCode(500);
                result.setMessage(role + "打开柜子失败");
                logger.warn("{} 打开柜子失败：cabinetName={}, phoneNumber={}", role, cabinetName, phoneNumber);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("系统错误，请稍后重试");
            logger.error("打开柜子失败：", e);
        }

        return result;
    }

    // 关闭柜子（送餐员：11位；取餐员：4位）
    @PostMapping("/close")
    public Result<Object> closeCabinet(@RequestBody CabinetInfo cabinetInfo) {
        Result<Object> result = new Result<>();

        String cabinetName = CabinetUtils.buildCabinetName(cabinetInfo.getCabinetName());
        String phoneNumber = cabinetInfo.getPhoneNumber();
        Integer cabinetId = cabinetInfo.getId();

        // 校验手机号格式
        if (phoneNumber.length() == 4 && !CabinetUtils.isValidPhoneTail(phoneNumber)) {
            result.setCode(400);
            result.setMessage("手机尾号格式不正确，请输入4位手机尾号");
            return result;
        } else if (phoneNumber.length() == 11 && !CabinetUtils.isValidPhoneNumber(phoneNumber)) {
            result.setCode(400);
            result.setMessage("手机号格式不正确，请输入11位有效手机号");
            return result;
        } else if (phoneNumber.length() != 4 && phoneNumber.length() != 11) {
            result.setCode(400);
            result.setMessage("手机号码格式不正确，请输入4位手机尾号或11位手机号码");
            return result;
        }

        if (cabinetId == null) {
            result.setCode(400);
            result.setMessage("cabinetId 不能为空");
            return result;
        }

        try {
            boolean isSuccess;
            String role;

            if (phoneNumber.length() == 4) {
                // 取餐员关闭柜子
                isSuccess = cabinetMapper.closeCabinetForPickup(cabinetName, cabinetId,phoneNumber);
                role = "取餐员";
            } else {
                // 送餐员关闭柜子
                isSuccess = cabinetMapper.closeCabinetForDeliveryman(cabinetName, phoneNumber);
                role = "送餐员";
            }

            if (isSuccess) {
                result.setCode(200);
                result.setMessage(role + "关闭柜子成功");
                logger.info("{} 关闭柜子成功：cabinetName={}, phoneNumber={}", role, cabinetName, phoneNumber);
            } else {
                result.setCode(500);
                result.setMessage(role + "关闭柜子失败");
                logger.warn("{} 关闭柜子失败：cabinetName={}, phoneNumber={}", role, cabinetName, phoneNumber);
            }
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("系统错误，请稍后重试");
            logger.error("关闭柜子失败：", e);
        }

        return result;
    }
}